package com.cloud.open.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.common.bean.PageInfo;
import com.cloud.open.config.CacheConfig;
import com.cloud.open.dao.AppDao;
import com.cloud.open.dto.AppQueryParamDTO;
import com.cloud.open.entity.App;
import com.cloud.open.service.AppAuthorizationService;
import com.cloud.open.service.AppService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 *  应用服务实现类
 * </p>
 *
 * @author wenjin
 * @since 2019-09-25
 */
@Service
public class AppServiceImpl extends ServiceImpl<AppDao, App> implements AppService {

    @Autowired
    private AppAuthorizationService appAuthorizationService;

    @Override
    public boolean checkNameExist(String name, Integer ignoreId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(App.APP_NAME, name);
        if (ignoreId != null) {
            wrapper.ne(App.ID, ignoreId);
        }
        List<App> appList = list(wrapper);
        if (CollectionUtils.isEmpty(appList)) {
            return false;
        }
        return true;
    }

    @Override
    public PageInfo<App> getPage(AppQueryParamDTO paramDTO) {
        QueryWrapper wrapper = new QueryWrapper();
        String searchKey = paramDTO.getSearchKey();
        if (!StringUtils.isEmpty(searchKey)) {
            wrapper.like(App.APP_NAME, searchKey);
            wrapper.or();
            wrapper.like(App.COMPANY_NAME, searchKey);
        }
        IPage page = page(new Page(paramDTO.getPageNo(), paramDTO.getPageSize()), wrapper);
        return new PageInfo(page);
    }

    @Override
    @Cacheable(cacheNames = CacheConfig.APP, key = "#appId")
    public App getByAppId(String appId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(App.APP_ID, appId);
        return getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        appAuthorizationService.deleteByAppId(id);
        return super.removeById(id);
    }
}
